package com.wensi.intelligentvoice.voice

import android.app.Service
import android.content.Intent
import android.os.Handler
import android.os.IBinder
import android.text.TextUtils
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.airbnb.lottie.LottieAnimationView
import com.wensi.helper.AppHelper
import com.wensi.helper.NotificationHelper
import com.wensi.helper.SoundHelper
import com.wensi.helper.WindowHelper
import com.wensi.intelligentvoice.R
import com.wensi.intelligentvoice.adapter.ChatListAdapter
import com.wensi.intelligentvoice.data.ChatListData
import com.wensi.intelligentvoice.entity.AppContants
import com.wensi.lib_voice.impl.OnAsrResultListener
import com.wensi.lib_voice.impl.OnNluResultListener
import com.wensi.lib_voice.manager.VoiceManager
import com.wensi.lib_voice.tts.VoiceTTS
import com.wensi.lib_voice.voiceEngine.VoiceEngineAnalyze
import com.wensi.lib_voice.words.WordTools
import com.wensi.utils.L
import org.json.JSONObject

/** 语音服务 */
class VoiceService: Service(), OnNluResultListener {

    private lateinit var fullWindowView: View
    private lateinit var mChatListView: RecyclerView
    private lateinit var mLottieView: LottieAnimationView
    private lateinit var tv_voice_tips: TextView
    private var mList = ArrayList<ChatListData>()
    private lateinit var chatAdapter: ChatListAdapter
    private val mHandler = Handler()
    override fun onCreate() {
        super.onCreate()
        L.i("语音服务启动")
        initService()
    }
    // 初始化语音服务
    private fun initService() {
        WindowHelper.initWindowHelper(this) // 初始化窗口
        fullWindowView = WindowHelper.getView(R.layout.layout_window_item)
        mChatListView = fullWindowView.findViewById(R.id.mChatListView)
        mLottieView = fullWindowView.findViewById(R.id.mLottieView)
        tv_voice_tips = fullWindowView.findViewById(R.id.tv_voice_tips)
        mChatListView.layoutManager = LinearLayoutManager(this)
        chatAdapter = ChatListAdapter(mList)
        mChatListView.adapter = chatAdapter

        VoiceManager.initManager(this, object: OnAsrResultListener{
            override fun updateUserText(text: String) {
                updateTips(text)
            }

            override fun wakeupReady() {
                L.i("====唤醒准备就绪====")
                addIntelligentText("唤醒引擎准备就绪")
            }

            override fun asrStartSpeak() {
                L.i("开始说话")
            }

            override fun asrStopSpeak() {
                L.i("停止说话")
                hideWindow()
            }

            override fun wakeupSuc(result: JSONObject) {
                L.i("唤醒成功 $result")
                wakeupAfter(result)
            }
            override fun asrResult(result: JSONObject) {
                L.i("在线识别结果 --result- $result ")
            }

            override fun nluResult(nlu: JSONObject) {
                L.i("语音识别结果  ---nlu- $nlu")
                addMineText(nlu.optString("raw_text"))
//                addIntelligentText(nlu.toString())
                VoiceEngineAnalyze.analyzeNlu(nlu, this@VoiceService)
            }

            override fun voiceErr(err: String) {
                L.i("发生错误 $err")
                hideWindow()
            }
        }) // 初始化百度语音合成

    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        bindNotification()
        // 兼容版本，但不能保证系统kill服务后，一定能再次重启
        return START_STICKY_COMPATIBILITY
    }
    override fun openApp(appName: String) {
        // 打开app
        if(!TextUtils.isEmpty(appName)) {
            L.i("====== 执行打开APP ======")
            val isOpen = AppHelper.launcherApp(appName)
            if (isOpen) addIntelligentText("正在为您打开$appName")
            else addIntelligentText("抱歉，无法为您打开$appName")
        }
        hideWindow()
    }

    override fun unInstallApp(appName: String) {
        // 卸载app
        if(!TextUtils.isEmpty(appName)) {
            L.i("====== 执行卸载APP ======")
            val isUninstall = AppHelper.unInstallApp(appName)
            if (isUninstall) addIntelligentText("正在为您卸载$appName")
            else addIntelligentText("抱歉，无法为您卸载$appName")
        }
    }

    override fun nluErr() {
        addIntelligentText(WordTools.noanswerWords())
    }

    // 绑定通知栏
    private fun bindNotification() {
        L.i("服务绑定前的启动~")
        startForeground(1000, NotificationHelper.bindVoiceService("服务运行中"))
    }
    override fun queryWeather() {
        // 通过VoiceEngineAnalyze.analyzeNlu语义结果，接口回调暴露出来，查询天气
        L.i("queryWeather 查询天气")
    }

    override fun otherAppHandle(appName: String) {
        // 其他app的逻辑操作处理
        // 跳转到应用市场
        val isIntent = AppHelper.intentAppStore(appName)
        if (isIntent)
            addIntelligentText("正在为您跳转到$appName")
        else
            addIntelligentText("抱歉，无法为您跳转到$appName")
    }


    // 唤醒词之后，显示窗口
    private fun showWindow() {
        L.i("=========显示窗口==========")
        mLottieView.playAnimation()
        WindowHelper.showWindowView(fullWindowView)

    }
    // 隐藏窗口
    private fun hideWindow() {
        L.i("=========隐藏窗口==========")
        mHandler.postDelayed({
            mLottieView.pauseAnimation()
            WindowHelper.hideWindowView(fullWindowView)
        }, 1 * 1000)
    }
    // 添加我的文本
    private fun addMineText(text: String) {
        val bean = ChatListData(AppContants.TYPE_MINE_TEXT, text)
        baseAddItem(bean)
    }
    // 添加智能语音的文本
    private fun addIntelligentText(text: String, ttsResultListener: VoiceTTS.OnTTSResultListener? = null) {
        VoiceManager.startSpeak(text) // 无法应答
        val bean = ChatListData(AppContants.TYPE_INTELLIGENT_TEXT, text)
        baseAddItem(bean)
        ttsResultListener?.ttsEnd()
    }
    // 添加天气预报文本
    private fun addWeatherText(text: String) {
        val bean = ChatListData(AppContants.TYPE_WEATHER_TEXT, text)
        baseAddItem(bean)
    }

    private fun baseAddItem(bean: ChatListData) {
        mList.add(bean)
        chatAdapter.notifyItemInserted(mList.size - 1)
    }
    // 更新提示语
    private fun updateTips(text: String) {
        tv_voice_tips.text = text
    }
    // 唤醒之后的工作
    private fun wakeupAfter(result: JSONObject) {
        showWindow() // 显示窗口
        updateTips("正在聆听...")
        // 当唤醒词是"小爱同学"的时候， 开始启动识别
        // 唤醒成功 {"errorDesc":"wakup success","errorCode":0,"word":"小爱同学"}
        val errorCode = result.optInt("errorCode")
        val word = result.optString("word")
        if (errorCode == 0 && (word == "小爱同学" || word == "小爱小爱")) {
            SoundHelper.playVoice(R.raw.record_start) // 播放滴声
            // 通过小爱同学唤醒成功 -  应答
            val text = WordTools.wakeupWords()
//            addIntelligentText(text)
            addIntelligentText(text, object : VoiceTTS.OnTTSResultListener{
                override fun ttsEnd() {
                    //应答结束，开始识别短语音
                    VoiceManager.startAsr()

                }
            })
        }
    }
}